from flask import Blueprint, render_template, request, redirect, url_for, jsonify, session
from models import UserModel
from models import BookModel
from models import ClassifierModel
from exts import db
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint("auth", __name__, url_prefix="/")


@bp.route("/", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("index.html")
    else:
        username = request.values.get('username')
        password = request.values.get('password')
        user = UserModel.query.filter_by(username=username).first()
        if not user or user.permissions == 3:
            return "error"
        if check_password_hash(user.password, password):
            session['nick_name'] = user.nickname
            session['user_name'] = user.username
            session['power'] = user.permissions
            session['user_id'] = user.id
            print("dsasd")
            return redirect(url_for("book_manage.books_getall"))
        else:
            return "error"


@bp.route("/")
def logout():
    session.clear()
    return render_template("index.html")



@bp.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template("register.html", status="True")
    else:
        username = request.values.get('username')
        password = request.values.get('password')
        users = UserModel.query.filter_by(username=username)
        if users.count() > 0:
            return "error"
        usr = UserModel(username=username, password=generate_password_hash(password))
        usr.nickname = username + "-sztu"
        db.session.add(usr)
        db.session.commit()
        return redirect(url_for("auth.login"))



